package com.hnepri.fang.ftx.write;

import com.hnepri.util.DBUtil;
import com.hnepri.util.FileUtil;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

/**
 * 把文件数据写入数据库
 */
public class WriteResidential {
    static List<String> getLines(String city) {
        List<String> ls = new ArrayList<>();
        String path = "E:\\小区\\" + city + "\\jianjie";
        File f = new File(path);
        File [] fs = f.listFiles();
        for(File tmp:fs) {
            ls.addAll(FileUtil.getLineList(tmp.getAbsolutePath(), "utf-8"));
        }
        return ls;
    }
    static void write2db(String city) {
        Connection con = null;
        PreparedStatement ps = null;
        List<String> lines = getLines(city);
        try {
            con = DBUtil.getConnection();
            con.setAutoCommit(false);
            String sql = "insert into xiaoqu(city,name,district,comarea,type,price,address,domain)" +
                    "values(?,?,?,?,?,?,?,?)";
            ps = con.prepareStatement(sql);

            int i = 0;
            for(String line:lines) {
                if (line == null || line.trim().equals(""))continue;
                i++;
                String [] datas = line.split("\\|");
                ps.setString(1, city);
                ps.setString(2, datas[0].trim());
                ps.setString(3, datas[1].trim());
                ps.setString(4, datas[2].trim());
                ps.setString(5, datas[3].trim());

                if (datas[4].trim().equals("")) {
                    ps.setNull(6, Types.NULL);
                } else {
                    ps.setDouble(6, Double.valueOf(datas[4].trim()));
                }

                ps.setString(7, datas[5].trim());
                ps.setString(8, datas[6].trim());

                ps.addBatch();
                if (i % 100 == 0) {
                    ps.executeBatch();
                }
            }
            ps.executeBatch();

            con.commit();
        } catch (Exception e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                DBUtil.closeResource(con, ps);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public static void main(String[] args) {
        write2db("jiyuan");
        //System.out.println(getLines().size());
    }
}
